package com.gavin.lingxi;

import android.content.Context;
import android.content.Intent;

import com.gavin.lingxi.rtc.call.LiveActivity;
import com.gavin.lingxi.rtclib.AbsRTCMsgClient;
import com.gavin.lingxi.rtclib.IRTCMsgClient;
import com.puppy.bingo.mqtt.MqttMsgService;
import com.puppy.bingo.mqtt.MqttTopic;
import com.puppy.bingo.mqtt.listener.IMqttClient;
import com.puppy.bingo.mqtt.listener.IMqttMsgListener;
import com.puppy.bingo.tools.StringUtils;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;
import org.mym.plog.PLog;

import java.util.Iterator;


public class WertcSdk extends AbsRTCMsgClient {

    private static final String TOPIC_RTC_SIGNAL_PREFIX = MqttTopic.CLIENT_TO_ROTBOT_TOPIC_PREFIX;
    private static WertcSdk instance;
    private IMqttClient mMqttClient;
    private String mCallUid;
    private String mUid = "";
    private Context mContext;


    private WertcSdk(Context context) {
        mContext = context;
        init(context);
    }

    public static void initialize(Context context){
        if(instance != null){
            throw new RuntimeException("you can only invoke initialize first");
        }
        instance = new WertcSdk(context);
    }

    public static WertcSdk getInstance() {
        if(instance == null){
            throw new RuntimeException("you must invoke initialize firstly");
        }
        return instance;
    }

    private void init(Context context) {
        mMqttClient = new MqttMsgService(context);
        mMqttClient.registerListener(new IMqttMsgListener() {
            @Override
            public void onMessageArrived(String topic, MqttMessage message) {
                try {
                    JSONObject payload = new JSONObject(message.toString());
                    PLog.objects(payload);
                    JSONObject msg = payload.getJSONObject("msg");
                    String type = msg.getString("type");
                    if (type.equals("joined")) {
                        String uid = msg.getString("uid");
                        setCallUid(uid);
                        toLiveActivity();
                    }
                    synchronized (listeners) {
                        Iterator<IRTCMsgClient.RTCMsgArrivedListener> it = listeners.iterator();
                        while (it.hasNext()) {
                            IRTCMsgClient.RTCMsgArrivedListener listener = it.next();
                            if (listener != null) {
                                listener.onRTCMsgArrived(msg);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
            }
        });
    }

    public void subRtcSignal() {
        if (mMqttClient == null) {
            PLog.e("mqttClient is null!");
            return;
        }
        String uid = getUserId();
        if (!StringUtils.isEmpty(uid)) {
            mMqttClient.subscribe(TOPIC_RTC_SIGNAL_PREFIX + uid);
        } else {
            PLog.e("uid is null");
        }

    }

    public void unSubRtcSignal() {
        if (mMqttClient == null) {
            PLog.e("mqttClient is null!");
            return;
        }
        String uid = getUserId();
        if (!StringUtils.isEmpty(uid)) {
            mMqttClient.unsubscribe(TOPIC_RTC_SIGNAL_PREFIX + uid);
        } else {
            PLog.e("uid is null");
        }

    }


    public void reconnect() {
        if (mMqttClient == null) {
            return;
        }
        mMqttClient.reconnect();
    }

    private void toLiveActivity() {
        Intent intent = new Intent(mContext, LiveActivity.class);
        intent.putExtra(RTCParam.INTENT_CALL_TYPE, RTCParam.TYPE_CALLEE);
        intent.putExtra(RTCParam.INTENT_USER_ID, getUserId());
        mContext.startActivity(intent);
    }

    public void setCallUid(String callUid){
        mCallUid = callUid;
    }

    public String getUserId() {
        return mUid;
    }

    public void setUserId(String uid){
        if(StringUtils.isEmpty(uid)){
            mUid = uid;
            WertcSdk.getInstance().unSubRtcSignal();
        }else if(!uid.equals(mUid)){
            mUid = uid;
            WertcSdk.getInstance().subRtcSignal();
        }
    }

    @Override
    public void sendRTCMsg(JSONObject msg) {
        try {
            JSONObject payload = new JSONObject();
            payload.put("msg", msg);
            PLog.objects(payload);
            if (mMqttClient != null) {
                MqttMessage mqttMessage = new MqttMessage();
                mqttMessage.setPayload(payload.toString().getBytes());
                if (!StringUtils.isEmpty(mCallUid)) {
                    mMqttClient.publish(TOPIC_RTC_SIGNAL_PREFIX + mCallUid, mqttMessage);
                } else {
                    PLog.e("CallID is null");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
